/*
 * MetodoDialog.java
 * 
 * Copyright (C) 2008 David Castellanos Serrano
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package dpoo.gui;

import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

import dpoo.figuras.Metodo;
import dpoo.figuras.ModVisi;
import dpoo.figuras.Parametro;
import dpoo.gui.ParametroDialog;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;

/**
 *
 * @author  david
 */
public class MetodoDialog extends javax.swing.JDialog {
    
    private Metodo metodo;
    
    //Modelo para el JList
    DefaultListModel paramsListModel;
    
    /**
     * Crea un nuevo MetodoDialog en blanco
     * @param parent
     * @param modal
     */
    public MetodoDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        
        //instancio un DefaultListModel e inicializo los componentes
        this.paramsListModel = new DefaultListModel();
        initComponents();
        initCheckNombre();
        
        //desactivo el botón de eliminar parámetro
        this.eliminarParametro.setEnabled(false);
        
        //instancio un nuevo método que será el que devuelva
        this.metodo = new Metodo("nuevoMetodo", Parametro.INT);
    }
    
    /**
     * Crea un nuevo MetodoDialog cargando los datos de un Metodo
     * @param parent
     * @param modal
     * @param metodo
     */
    public MetodoDialog(java.awt.Frame parent, boolean modal, Metodo metodo) {
        super(parent, modal);
        
        //instancio un DefaultListModel e inicializo los componentes
        this.paramsListModel = new DefaultListModel();
        initComponents();
        
        //me guardo la referencia del Metodo que voy a modificar
        this.metodo = metodo;
        
        //desactivo el botón de eliminar parámetro
        this.eliminarParametro.setEnabled(false);
        
        //cargo en el cuadro de diálogo los datos
        this.cargarDatos();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        visiGroup = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        nombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        visiPaquete = new javax.swing.JRadioButton();
        visiPrivada = new javax.swing.JRadioButton();
        visiPublica = new javax.swing.JRadioButton();
        visiProtegido = new javax.swing.JRadioButton();
        jLabel4 = new javax.swing.JLabel();
        modAbstracta = new javax.swing.JCheckBox();
        modFinal = new javax.swing.JCheckBox();
        modEstatico = new javax.swing.JCheckBox();
        String[] tipos = {"int", "float", "double", "boolean", "String"};
        tipoDevuelto = new javax.swing.JComboBox(tipos);
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListParametros = new javax.swing.JList(this.paramsListModel);
        anadirParametro = new javax.swing.JButton();
        cancelar = new javax.swing.JButton();
        guardar = new javax.swing.JButton();
        eliminarParametro = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nuevo método");
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(496, 358));

        jLabel1.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel1.setText("Nombre:");

        jLabel2.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel2.setText("Tipo devuelto:");

        jLabel3.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel3.setText("Visibilidad:");

        visiGroup.add(visiPaquete);
        visiPaquete.setSelected(true);
        visiPaquete.setText("Paquete");

        visiGroup.add(visiPrivada);
        visiPrivada.setText("Privada");

        visiGroup.add(visiPublica);
        visiPublica.setText("Pública");

        visiGroup.add(visiProtegido);
        visiProtegido.setText("Protegido");

        jLabel4.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel4.setText("Modificadores:");

        modAbstracta.setText("Abstracto");

        modFinal.setText("Final");

        modEstatico.setText("Estático");

        jLabel5.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel5.setText("Parámetros:");

        jListParametros.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListParametrosValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jListParametros);

        anadirParametro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dpoo/gui/list-add.png"))); // NOI18N
        anadirParametro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                anadirParametroActionPerformed(evt);
            }
        });

        cancelar.setText("Cancelar");
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });

        guardar.setText("Guardar");
        guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarActionPerformed(evt);
            }
        });

        eliminarParametro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dpoo/gui/list-remove.png"))); // NOI18N
        eliminarParametro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eliminarParametroActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nombre, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(modFinal)
                            .addComponent(modAbstracta)
                            .addComponent(modEstatico)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(visiPaquete)
                            .addComponent(visiPrivada))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(visiPublica)
                            .addComponent(visiProtegido)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tipoDevuelto, 0, 371, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(anadirParametro)
                            .addComponent(eliminarParametro)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(guardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tipoDevuelto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(visiPaquete)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(visiPrivada))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(visiProtegido)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(visiPublica)))
                    .addComponent(jLabel3))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(modAbstracta))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(modFinal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(modEstatico)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(anadirParametro)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(eliminarParametro))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelar)
                    .addComponent(guardar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    /**
     * Inicializa el chequeo del nombre del Atributo en el AtributoDialog
     */
    private void initCheckNombre() {
        //estoy al tanto de los cambios que ocurrieran en el nombre del atributo
        Document doc = this.nombre.getDocument();
        doc.addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent arg0) {
                nombreTextChange();
            }

            public void removeUpdate(DocumentEvent arg0) {}

            public void changedUpdate(DocumentEvent arg0) {
                nombreTextChange();
            }
        });
        
        //la venganza se sirve fría: impido que el usuario cierre la ventana sin usar los botones guardar o cancelar
        this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    }
    
    
    private void guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarActionPerformed
        if(this.comprobarNombre()) {
            //actualizo el objeto Metodo del cual tengo referencia con los nuevos datos del cuadro de diálogo
            //nombre del Metodo
            this.metodo.setNombre(this.nombre.getText());

            //valor devuelto
            this.metodo.setTipoDevuelto(this.tipoDevuelto.getSelectedIndex());

            //extraigo el objeto ModVisi asociado al método
            ModVisi modVisi = this.metodo.getModVisi();

            //cargo los modificadores del diálogo para el método
            modVisi.setModAbstracto(this.modAbstracta.isSelected());
            modVisi.setModEstatico(this.modEstatico.isSelected());
            modVisi.setModFinal(this.modFinal.isSelected());

            //y la visibilidad asociada
            if(this.visiPaquete.isSelected()) {
                modVisi.setVisibilidad(ModVisi.PAQUETE);
            }
            if(this.visiPrivada.isSelected()) {
                modVisi.setVisibilidad(ModVisi.PRIVADO);
            }
            if(this.visiProtegido.isSelected()) {
                modVisi.setVisibilidad(ModVisi.PROTEGIDO);
            }
            if(this.visiPublica.isSelected()) {
                modVisi.setVisibilidad(ModVisi.PUBLICO);
            }

            //una vez hecho todo esto, ya puedo ocultar el cuadro de diálogo
            this.setVisible(false);
        } else {
            this.nombreTextChange();
        }
    }//GEN-LAST:event_guardarActionPerformed
    
    private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
        this.metodo = null;
        this.setVisible(false);
    }//GEN-LAST:event_cancelarActionPerformed
    
    private void anadirParametroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_anadirParametroActionPerformed
        ParametroDialog paramDialog = new ParametroDialog(this, true);
        paramDialog.setVisible(true);
        
        //recojo el Parametro del ParametroDialog
        Parametro param = paramDialog.getParametro();
                System.out.println(param);
        //obtengo un puntero al Vector de parámetros del Metodo
        Vector<Parametro> vParam = this.metodo.getParametros();
        
       //añado el Parametro al Vector de parámetros y al JList del MetodoDialog
        vParam.add(param);
        this.paramsListModel.addElement(param);
        
        //libero recursos del ParametroDialog y repinto el JList
        paramDialog.dispose();
        this.jListParametros.repaint();
    }//GEN-LAST:event_anadirParametroActionPerformed
    
    private void eliminarParametroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminarParametroActionPerformed
        //obtengo un punto al Parametro seleccionado en el JList
        Parametro param = (Parametro) this.jListParametros.getSelectedValue();
        
        //obtengo un puntero al Vector de parámetros del Metodo
        Vector<Parametro> vParam = this.metodo.getParametros();
        
        //elimino el Parametro tanto del Vector como del modelo del JList
        vParam.remove(param);
        this.paramsListModel.removeElement(param);
        
        //repinto el JList
        this.jListParametros.repaint();
    }//GEN-LAST:event_eliminarParametroActionPerformed

private void jListParametrosValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListParametrosValueChanged
    if(this.jListParametros.getSelectedIndex() == -1) {
        this.eliminarParametro.setEnabled(false);
    } else {
        this.eliminarParametro.setEnabled(true);
    }
}//GEN-LAST:event_jListParametrosValueChanged
    
    /**
     * Carga los datos de un Metodo en un MetodoDialog
     */
    private void cargarDatos() {
        //nombre del metodo
        this.nombre.setText(this.metodo.getNombre());
        
        //tipo devuelto
        this.tipoDevuelto.setSelectedIndex(this.metodo.getTipoDevuelto());
        
        //extraigo el objeto ModVisi del método...
        ModVisi modVisi = this.metodo.getModVisi();
        
        //modificadores
        this.modAbstracta.setSelected(modVisi.getModAbstracto());
        this.modEstatico.setSelected(modVisi.getModEstatico());
        this.modFinal.setSelected(modVisi.getModFinal());
        
        //visibilidad
        switch(modVisi.getVisibilidad()) {
            case ModVisi.PAQUETE:
                this.visiPaquete.setSelected(true);
                break;
            case ModVisi.PRIVADO:
                this.visiPrivada.setSelected(true);
                break;
            case ModVisi.PROTEGIDO:
                this.visiProtegido.setSelected(true);
                break;
            case ModVisi.PUBLICO:
                this.visiPublica.setSelected(true);
                break;
        }
        
        //añado los parámetros al modelo del JList
        for(Parametro param : this.metodo.getParametros()) {
            this.paramsListModel.addElement(param);
        }
    }
    
    
    /**
     * Devuelve un nuevo Metodo con los datos que hubiera en el MetodoDialog
     * @return
     */
    public Metodo getMetodo() {
        return this.metodo;
    }
    

    //COMPROBAR QUE EL CONTENIDO DEL AtributoDialog ES CORRECTO
    /**
     * Comprueba que el nombre del Atributo sea correcto
     * @return
     */
    private boolean comprobarNombre() {
        //Debe comenzar con una letra minúscula, y después tener letras, números o _
        Pattern pc = Pattern.compile("\\p{Lower}+\\w*");
        Matcher m = pc.matcher(this.nombre.getText());
        
        return m.matches();
    }
    
    
    /**
     * Si el nombre del método es incorrecto muestra un cuadro de diálogo informando al usuario
     */
    private void nombreTextChange() {
        if(!this.comprobarNombre()) {
            String msgText = "<html>Para que el nombre de un método sea válido, debe cumplir las siguientes condiciones:<ul>" +
                "<li>Debe comenzar con una letra minúscula (a-z).</li>" +
                "<li>Constar únicamente de letras (a-z, A-Z), números (0-9) o el caracter _.</li><ul></html>";
            JOptionPane.showMessageDialog(this, msgText, "Nombre de método incorrecto", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton anadirParametro;
    private javax.swing.JButton cancelar;
    private javax.swing.JButton eliminarParametro;
    private javax.swing.JButton guardar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JList jListParametros;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JCheckBox modAbstracta;
    private javax.swing.JCheckBox modEstatico;
    private javax.swing.JCheckBox modFinal;
    private javax.swing.JTextField nombre;
    private javax.swing.JComboBox tipoDevuelto;
    private javax.swing.ButtonGroup visiGroup;
    private javax.swing.JRadioButton visiPaquete;
    private javax.swing.JRadioButton visiPrivada;
    private javax.swing.JRadioButton visiProtegido;
    private javax.swing.JRadioButton visiPublica;
    // End of variables declaration//GEN-END:variables
    
}
